<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
      <a-layout-content class="flex flex-col lg:h-full relative w-full">
        <div ref="searchRef">

        </div>
        <div class="table-header lg:flex justify-between mb-2">
          <a-space class="lg:flex block lg:inline-block">
            <a-button v-auth="['region/delete']" type="primary" status="danger" size="small">
              <template #icon><icon-delete /></template>批量删除
            </a-button>
          </a-space>
          <a-space class="lg:mt-0 mt-2">
            <a-tooltip content="刷新表格"><a-button shape="circle" @click="refresh"><icon-refresh /></a-button></a-tooltip>
            <a-tooltip content="设置"><a-button shape="circle" @click="setTableColumns"><icon-settings /></a-button></a-tooltip>
          </a-space>
        </div>
        <div ref="tableContainerRef">
          <a-table
            ref="tableRef"
            row-key="id"
            :loading="loading"
            :pagination="false"
            :data="renderData"
            :bordered="{ wrapper: true, cell: true }"
            :row-selection="rowSelection"
            :scroll="tableScroll"
            column-resizable
          >
            <template #columns>
              <vue-table-column :columns="columns">
                <template #status="{ record }">
                  <a-switch v-model="record.status" :checked-value="1" :unchecked-value="2" @change="isActivate(record)"/>
                </template>
                <template #operations="{ record }">
                  <a-space>
                    <a-button type="primary" status="warning" size="small" @click="download(record)"><template #icon><icon-to-bottom /></template>下载</a-button>
                    <a-popconfirm content="确定要还原这条备份数据吗？" type="warning" position="br" @ok="doImport(record)">
                      <a-button type="primary" :class="`btn--${record.name}`" size="small">
                        <template #icon><icon-arrow-left /></template>还原
                      </a-button>
                    </a-popconfirm>
                    <a-popconfirm content="确定要删除这条备份数据吗？" type="warning" position="br" @ok="del(record)">
                      <a-button type="primary" status="danger" size="small"><template #icon><icon-delete /></template>删除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </vue-table-column>
            </template>
          </a-table>
        </div>
      </a-layout-content>
    </a-spin>

    <SetColumn ref="setColumnRef" :columns="columns" @update:columns="updateColumns"/>
  </div>
</template>

<script setup>
  import { ref, reactive, h, compile, nextTick, onMounted, onUnmounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { workAreaHeight, downloadFile } from '@/utils/index';
  import tool from '@/utils/tool';
  import { apiImportList, apiImport, apiDel } from '@/api/database';
  import VueTableColumn from '@/components/table/table-column.vue';
  import SetColumn from '@/components/table/set-column.vue';

  const { loading, setLoading } = useLoading(false);
  const baseColumns = [
    {
      title: '序号', dataIndex: 'numbers', width: 80,
      align: 'center', fixed: 'left',
    },
    {
      title: '备份文件名称', dataIndex: 'name', width: 200,
      align: 'center',
      ellipsis: true, tooltip: true,
    },
    {
      title: '卷数', dataIndex: 'part',  width: 100,
      align: 'center',
    },
    {
      title: '压缩', dataIndex: 'compress',  width: 100,
      align: 'center',
    },
    {
      title: '数据大小', dataIndex: 'size',  width: 100,
      align: 'center',
    },
    {
      title: '备份时间', dataIndex: 'mtime', width: 160,
      align: 'center',
    },
    {
      title: '操作', dataIndex: 'operations', width: 240,
      align: 'center', fixed: 'right',
      slotName: 'operations',
    },
  ];
  const columns = ref(tool.local.get('columns-database-import') || baseColumns);
  const renderData = ref([]);
  const rowSelection = reactive({
    type: 'checkbox',
    selectedRowKeys: [],
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();
  const setColumnRef = ref();
  const searchHeight = ref(0);

  const isReset = ref(true); // 是否重置
  let selectionKeys = []; // 选中项ID
  const spinLoading = ref(false);
  const spinTip = ref();

  const settingFixedPage = () => {
    const workHeight = workAreaHeight();
    const tableHeight = workHeight - searchHeight.value;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  };
  const toggleSearch = async () => {
    const dom = searchRef.value?.style;
    if (dom) {
      showSearch.value = !showSearch.value;
      await nextTick(() => {
        searchHeight.value = searchRef.value.offsetHeight;
        settingFixedPage();
      });
    }
  };
  const setTableColumns = () => {
    setColumnRef.value.init();
  };
  const updateColumns = (data) => {
    columns.value = data;
    tool.local.set('columns-database-import', columns.value);
  };

  // 列表
  const fetchData = async (
    params = {}
  ) => {
    setLoading(true);
    await reset();
    try {
      const { data } = await apiImportList(params);
      renderData.value = data.data;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 还原
  const doImport = async (row) => {
    setLoading(true);
    await apiImport({
      time: row.time,
      filepath: row.filepath,
    }).then(res => {
      restore(res.data, row);
    }).catch(() => {
      setLoading(false);
    });

    window.onbeforeunload = function () {
      return '正在还原数据库，请不要关闭！';
    };
  };
  // 删除
  const del = async (row) => {
    setLoading(true);
    try {
      await apiDel({
        time: row.time,
        filepath: row.filepath,
      });
    } catch (err) {
      setLoading(false);
    } finally {
      await fetchData();
      setLoading(false);
    }
  };
  // 下载
  const download = async (row) => {
    downloadFile(row.full_filepath);
  };

  // 恢复
  const restore = async (data, row) => {
    if (data.status === -1) {
      // 初始化
      await apiImport({
        part: data.part,
        start: data.start,
        time: data.time,
      }).then(res2 => {
        restore(res2.data, row);
      }).catch(() => {
        setLoading(false);
      });
    } else if (data.status === 1) {
      // 开始恢复
      setTimeout(() => {
        setLoading(false);
        document.getElementsByClassName(`btn--${row.name}`)[0].innerHTML = data.info;
      }, 2000);
      if (data.part) {
        await apiImport({
          part: data.part,
          start: data.start,
        }).then(res2 => {
          restore(res2.data, row);
        }).catch(() => {
          setLoading(false);
        });
      } else {
        window.onbeforeunload = function () {
          return null;
        }
      }
    }
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };
  // 刷新
  const refresh = async () => {
    await fetchData();
  };

  onMounted(async () => {
    await fetchData();
    window.addEventListener('resize', resizeHandler, false);
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
</script>

<script>
  export default {
    name: 'DatabaseImport',
  };
</script>

<style scoped lang="less">

</style>
